package cn.iocoder.an.module.business.service.equipmentkeeptype;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.an.framework.common.util.collection.CollectionUtils;
import cn.iocoder.an.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.an.module.business.controller.admin.equipmentmanage.vo.ImportRespVO;
import cn.iocoder.an.module.business.dal.dataobject.equipmentkeepsetting.EquipmentKeepSettingDO;
import cn.iocoder.an.module.business.dal.mysql.equipmentkeepsetting.EquipmentKeepSettingMapper;
import cn.iocoder.an.module.business.enums.MaintenanceStatusEnum;
import io.micrometer.common.util.StringUtils;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import cn.iocoder.an.module.business.controller.admin.equipmentkeeptype.vo.*;
import cn.iocoder.an.module.business.dal.dataobject.equipmentkeeptype.EquipmentKeepTypeDO;
import cn.iocoder.an.framework.common.pojo.PageResult;
import cn.iocoder.an.framework.common.pojo.PageParam;
import cn.iocoder.an.framework.common.util.object.BeanUtils;

import cn.iocoder.an.module.business.dal.mysql.equipmentkeeptype.EquipmentKeepTypeMapper;

import static cn.iocoder.an.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.an.module.business.enums.ErrorCodeConstants.*;

/**
 * 设备保养分类 Service 实现类
 *
 * @author zzy
 */
@Service
@Validated
public class EquipmentKeepTypeServiceImpl implements EquipmentKeepTypeService {

    @Resource
    private EquipmentKeepTypeMapper equipmentKeepTypeMapper;

    @Resource
    private EquipmentKeepSettingMapper equipmentKeepSettingMapper;

    @Override
    public Long createEquipmentKeepType(EquipmentKeepTypeSaveReqVO createReqVO) {
        // 插入
        EquipmentKeepTypeDO equipmentKeepType = BeanUtils.toBean(createReqVO, EquipmentKeepTypeDO.class);
        equipmentKeepTypeMapper.insert(equipmentKeepType);

        // 返回
        return equipmentKeepType.getId();
    }

    @Override
    public void updateEquipmentKeepType(EquipmentKeepTypeSaveReqVO updateReqVO) {
        // 校验存在
        validateEquipmentKeepTypeExists(updateReqVO.getId());

        //保养分类、保养项目及保养类型状态不同步：
        //① 保养分类禁用状态下，对应的保养项目状态自动变更为【禁用】
        //② 保养项目禁用状态下，保养类型配置时应无法选中
        if (updateReqVO.getStatus() != null) {
            LambdaQueryWrapperX<EquipmentKeepSettingDO> queryWrapperX = new LambdaQueryWrapperX<>();
            queryWrapperX.eq(EquipmentKeepSettingDO::getKeepType, updateReqVO.getId());
            List<EquipmentKeepSettingDO> equipmentKeepSettingDOS = equipmentKeepSettingMapper.selectList(queryWrapperX);
            for (EquipmentKeepSettingDO equipmentKeepSettingDO : equipmentKeepSettingDOS) {
                equipmentKeepSettingDO.setStatus(updateReqVO.getStatus());
            }
            if (equipmentKeepSettingDOS != null && !equipmentKeepSettingDOS.isEmpty()) {
                equipmentKeepSettingMapper.updateBatch(equipmentKeepSettingDOS);
            }

        }
        // 更新
        EquipmentKeepTypeDO updateObj = BeanUtils.toBean(updateReqVO, EquipmentKeepTypeDO.class);
        equipmentKeepTypeMapper.updateById(updateObj);
    }

    @Override
    public void deleteEquipmentKeepType(Long id) {
        // 校验存在
        validateEquipmentKeepTypeExists(id);

        //判断在保养项设置中有没有绑定

        LambdaQueryWrapperX<EquipmentKeepSettingDO> queryWrapperX = new LambdaQueryWrapperX<>();
        queryWrapperX.eq(EquipmentKeepSettingDO::getKeepType, id);
        List<EquipmentKeepSettingDO> equipmentKeepSettingDOS = equipmentKeepSettingMapper.selectList(queryWrapperX);
        if (equipmentKeepSettingDOS != null && !equipmentKeepSettingDOS.isEmpty()) {
            throw exception(KEEP_DELETE_NOT);
        }
        // 删除
        equipmentKeepTypeMapper.deleteById(id);
    }

    @Override
        public void deleteEquipmentKeepTypeListByIds(List<Long> ids) {
        // 删除
        equipmentKeepTypeMapper.deleteByIds(ids);
        }


    private void validateEquipmentKeepTypeExists(Long id) {
        if (equipmentKeepTypeMapper.selectById(id) == null) {
            throw exception(EQUIPMENT_KEEP_TYPE_NOT_EXISTS);
        }
    }

    @Override
    public EquipmentKeepTypeDO getEquipmentKeepType(Long id) {
        return equipmentKeepTypeMapper.selectById(id);
    }

    @Override
    public PageResult<EquipmentKeepTypeDO> getEquipmentKeepTypePage(EquipmentKeepTypePageReqVO pageReqVO) {
        return equipmentKeepTypeMapper.selectPage(pageReqVO);
    }

    @Override
    public List<EquipmentKeepTypeDO> getEquipmentKeepTypeList() {
        LambdaQueryWrapperX<EquipmentKeepTypeDO> queryWrapperX = new LambdaQueryWrapperX<>();
        queryWrapperX.eq(EquipmentKeepTypeDO::getStatus,1);
        return equipmentKeepTypeMapper.selectList(queryWrapperX);
    }

    @Override
    public List<EquipmentKeepTypeDO> getEquipmentKeepTypeListNew() {
        LambdaQueryWrapperX<EquipmentKeepTypeDO> queryWrapperX = new LambdaQueryWrapperX<>();
        return equipmentKeepTypeMapper.selectList(queryWrapperX);
    }

    @Override
    public ImportRespVO importList(List<EquipmentKeepTypeImportExcelVO> list, boolean isUpdateSupport) {
        // 1.1 参数校验
        if (CollUtil.isEmpty(list)) {
            throw exception(IMPORT_EQUIPMENT_MANAGE_NOT_EXISTS);
        }


        //2.记录成功或失败记录
        ImportRespVO respVO = ImportRespVO.builder().insertNameList(new ArrayList<>())
                .updateNameList(new ArrayList<>()).failureMap(new LinkedHashMap<>()).build();

        AtomicInteger count = new AtomicInteger(1);
        list.forEach(equipment -> {
            count.incrementAndGet();//记录行号

            // 2.1.2 校验名称
            if (StringUtils.isEmpty(equipment.getName())) {
                respVO.getFailureMap().put("第" + count + "行数据", "分类名称不能为空!");
                return;
            }

            // 2.1.3 校验状态
            if (equipment.getStatus() == null) {
                respVO.getFailureMap().put("第" + count + "行数据", "状态不能为空!");
                return;
            }

            equipmentKeepTypeMapper.insert(BeanUtils.toBean(equipment, EquipmentKeepTypeDO.class));
            respVO.getInsertNameList().add(equipment.getName());
        });
        return respVO;
    }

}